#include <iostream>
#include <unistd.h>
#include <fstream>
#include "person.pb.h"
using namespace std;
using namespace test;
string pro_str;
void set_person()
{
    AddressBook obj;

    Person *p1 = obj.add_person();
    p1->set_name("mike");
    p1->set_id(1);
    //p1->set_email("mike@qq.com")
    *p1->mutable_email()="mike@qq.com";

    Person::PhoneNumber * phone1 = p1->add_phone_number();
    phone1->set_m_phone_number("112");
    phone1->set_m_type(Person::MOBILE);

    phone1 = p1->add_phone_number();
    phone1->set_m_phone_number("110");
    phone1->set_m_type(Person::WORK);

    //add info 
    infopack::Info *p_info = p1->mutable_tmp();
    p_info->set_m_addr("sz");
    p_info->set_m_group("first");

    Person *p2 = obj.add_person();
    p2->set_name("mike2");
    p2->set_id(2);
    *p2->mutable_email()="mike2@qq.com";

    phone1 = p2->add_phone_number();
    phone1->set_m_phone_number("210");
    phone1->set_m_type(Person::HOME);

    //add info 
    p_info = p2->mutable_tmp();
    p_info->set_m_addr("gz");
    p_info->set_m_group("second");
    fstream output("pro_fstream", ios::out | ios::trunc | ios::binary);
    if(! output)
    {
        cerr << "set err when write to stream\n";
        exit(0);
    }
    obj.SerializeToOstream(&output);
    output.close();

}

void get_person()
{
    fstream read_stream("pro_fstream",ios::in|ios::binary);
    if(!read_stream)
    {
        cerr<<"get err when read from stream\n";
        exit(0);
    }
    AddressBook obj;
    obj.ParseFromIstream(&read_stream);
    read_stream.close();        

    int len = obj.person_size();
    cout << "person size:"<<len<<endl;
    int i = 0;
    for(i = 0; i<len; ++i)
    {
        cout << "第" << i <<"个同学的信息如下：" <<endl;
    	Person p = obj.person(i);
        cout << "name:"<<p.name()<<endl;
        cout << "id:"<<p.id()<<endl;
        cout << "email:"<<p.email()<<endl;
        int _phone_num = p.phone_number_size();
        int j = 0;
        for(;j<_phone_num;++j)
        {
            Person::PhoneNumber q = p.phone_number(j);
            cout<<"phone:"<<q.m_phone_number()<<"  phone type:"<<Person::PhoneType_Name(q.m_type()) <<endl;
        }
        //get info
        infopack::Info info = p.tmp();
        cout <<"addr:"<< info.m_addr()<<endl;
        cout <<"group:"<< info.m_group()<<endl;
    }

}

int main()
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    set_person();
    get_person();
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}
